const pool = require("@/db");
const table = require("@/db/table");

async function getMenus({ page_index = 1, page_size = 20 }) {
  return await pool
    .select("*")
    .from(table.MENU)
    .queryListWithPaging(page_index, page_size);
}

async function getMenu({ id, code, parent_id }) {
  return await pool
    .select("*")
    .from(table.MENU)
    .where("id", id, "eq", "ifHave")
    .where("code", code, "eq", "ifHave")
    .where("parent_id", parent_id, "eq", "ifHave")
    .queryRow();
}

async function addMenu(menu) {
  const result = await pool
    .insert(table.MENU, {
      name: menu.name,
      code: menu.code,
      route: menu.route,
      parent_id: menu.parent_id,
      type: menu.type,
      icon: menu.icon,
      sort: menu.sort,
      file_path: menu.file_path,
      level: menu.level,
      path: menu.path,
      created_time: new Date(),
      updated_time: new Date(),
    })
    .execute();
  return result.insertId;
}

async function updateMenu(id, menu) {
  const result = await pool
    .update(table.MENU, {
      name: menu.name,
      code: menu.code,
      route: menu.route,
      parent_id: menu.parent_id,
      type: menu.type,
      icon: menu.icon,
      sort: menu.sort,
      file_path: menu.file_path,
      level: menu.level,
      path: menu.path,
    })
    .where("id", id)
    .execute();
  return result.affectedRows > 0;
}

async function deleteMenu(id) {
  const result = await pool.delete(table.MENU).where("id", id).execute();
  return result.affectedRows > 0;
}

module.exports = { getMenus, getMenu, addMenu, updateMenu, deleteMenu };
